import {
  Controller,
  Get,
  Post,
  Body,
  Param,
  Request,
  UseGuards,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ChatService } from './chat.service';
import { MessageService } from './message.service';

@Controller('chat')
export class ChatController {
  constructor(
    private readonly chatService: ChatService,
    private readonly messageService: MessageService,
  ) {}

  // 获取用户会话列表
  @UseGuards(AuthGuard('jwt'))
  @Get('conversations')
  async getConversations(@Request() req) {
    try {
      const userId = parseInt(req.user.id);
      const conversations =
        await this.chatService.getConversationsByUserId(userId);
      return {
        success: true,
        data: conversations,
        message: '获取会话列表成功',
      };
    } catch (error) {
      return {
        success: false,
        data: [],
        message: '获取会话列表失败: ' + error.message,
      };
    }
  }

  // 获取会话中的消息
  @UseGuards(AuthGuard('jwt'))
  @Get('messages/:conversationId')
  async getMessages(@Param('conversationId') conversationId: string) {
    try {
      const messages = await this.messageService.getMessagesByConversationId(
        parseInt(conversationId),
      );
      return {
        success: true,
        data: messages,
        message: '获取消息成功',
      };
    } catch (error) {
      return {
        success: false,
        data: [],
        message: '获取消息失败: ' + error.message,
      };
    }
  }

  // 发送消息
  @UseGuards(AuthGuard('jwt'))
  @Post('messages')
  async sendMessage(
    @Request() req,
    @Body() body: { receiverId: number; content: string; messageType: string },
  ) {
    // 注意：这里需要从JWT token中获取发送者信息
    return {
      success: false,
      message: '发送消息功能尚未完全实现',
    };
  }
}
